<?php
namespace Common\Model;
use Think\Model;

/**
 * Created by PhpStorm.
 * User: qufan
 * Date: 2016/12/7 0007
 * Time: 21:27
 */
class UserModel extends Model
{
    protected $_auto = array(
//        array('org_id', 0),
        array('add_time', 'time_format', self::MODEL_INSERT, 'function', NOW_TIME ),
        array('state',1),
//        array('time_make','time_format', self::MODEL_INSERT, 'function', NOW_TIME),
//        array('time_edit', 'time_format',self::MODEL_BOTH, 'function', NOW_TIME),
//        array('res',USER_RES_CREATE, self::MODEL_INSERT),
//        array('att_login', USER_ATT_LOGIN_NORMAL, self::MODEL_INSERT),
    );

    protected $_validate = array(
        array('user_name', '', '账号名称已经存在！', self::EXISTS_VALIDATE, 'unique', self::MODEL_BOTH)
    );

    /**
     * 创建用户
     * @param $data
     * @return int|mixed|string
     */
    public function createUser($data){
        if ($this->create($data)){
            $uid = $this->add();
            return $uid?$uid:0;
        }else{
            return $this->getError();
        }
    }

    /**
     * 登录操作
     * @param $user_name
     * @param $password
     * @return int|mixed
     */
    public function login($user_name, $password){
        $map['user_name'] = $user_name;
        $user = $this->where($map)->find();
        if(is_array($user)){
            if ($password === $user['password']){
                if ($user['state'] > 1){//删除或者禁用
                    return -$user['state'];
                }

                $data['last_login_ip'] = $user['end_login_ip'];
                $data['end_login_ip'] = get_client_ip();
                $data['last_login_time'] = $user['end_login_time'];
                $data['end_login_time'] = time_format(NOW_TIME);
                $this->where("user_id={$user['user_id']}")->save($data);
                $this->autoLogin($user);
                return $user['user_id'];
            }else{
                return 0; //密码不正确
            }
        }else{
            return -1; //用户不存在
        }
    }


    private function autoLogin($user){
        $auth = array(
            'uid'   => $user['user_id'],
            'username' => $user['user_name'],
            'realname'  => $user['real_name'],
            'role_id'   => $user['role_id'],
            'chat_id'   => C('IM_CHAT_KEY') . $user['user_id']
        );
        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));
    }

    public function logout(){
        session('user_auth', null);
        session('user_auth_sign', null);
    }

    public function update($data = null){
        $data = $this->token(false)->create($data);
        if (empty($data)){
            return false;
        }

        if (empty($data['user_id'])){
            $id = $this->add();
            if (!$id){
                $this->error = '新增用户出错';
                return false;
            }
            $data['user_id'] = $id;
        }else{
            $status = $this->save();
            if (false === $status){
                $this->error = '更新出错出错';
                return false;
            }
        }
        $data['icon'] = $this->checkIcon($data['user_id']);
        return $data;
    }

    public function checkIcon($id){
        $data = $this->find($id);
        if($data['sex'] == 1 && $data['icon'] == C('DEFAULT_USER_ICON.MALE')){
            return $data['icon'];
        }
        if($data['sex'] == 2 && $data['icon'] == C('DEFAULT_USER_ICON.FEMALE')){
            return $data['icon'];
        }
        if(empty($data['icon'])){
            if($data['sex'] == 1){
                $data['icon'] = C('DEFAULT_USER_ICON.MALE');
            }else{
                $data['icon'] = C('DEFAULT_USER_ICON.FEMALE');
            }
            $this->save($data);
            return $data['icon'];
        }else{
            $to = $id . '_' . $data['user_name'];
            if(renameFile(true, $data['icon'], $to )){
                $data['icon'] = $to;
                $this->save($data);
                return $to;
            }else{
                return $data['icon'];
            }
        }

    }

    public function verifyUser($uid, $password_in){
        $user = $this->find($uid);
        if($user['password'] == $password_in){
            return true;
        }else{
            return false;
        }
    }

    public function changePwd($uid, $password_in, $new_password){
        $user = $this->find($uid);
        if($user['password'] == $password_in){
            $user['password'] = $new_password;
            $this->save($user);
            return true;
        }else{
            $this->error = '用户密码不正确';
            return false;
        }
    }

}